import React, { useEffect, useState, useRef } from 'react'
import { PageContainer } from '@ant-design/pro-components'
import { useModel, history, useSearchParams } from '@umijs/max'
import {
  Form,
  Checkbox,
  Space,
  Button,
  Card,
  Divider,
  Input,
  Radio,
  InputNumber,
  Select,
  Cascader,
  App,
  TimePicker
} from 'antd'
import dayjs from 'dayjs'
import customParseFormat from 'dayjs/plugin/customParseFormat'

import styles from './Deliver.less'
dayjs.extend(customParseFormat)

const formItemLayout = {
  labelCol: { span: 3 },
  wrapperCol: { span: 20 }
}
let timer = null
const originInitial = {
  status: 1
}
const { RangePicker } = TimePicker

//  地图定位组件
const LocationPickup = props => {
  const { value, onChange, disabled, triggerCallback } = props

  useEffect(() => {
    initMap()
  }, [])

  const initMap = () => {
    try {
      const map = new AMap.Map('container')
      const placeSearch = new AMap.PlaceSearch({
        map: map,
        pageSize: 4, // 单页显示结果条数
        pageIndex: 1, // 页码
        panel: 'panel', // 结果列表将在此容器中进行展示。
        autoFitView: true,
        extensions: 'all'
      })
      const mapConfig = {
        showIndoorMap: false,
        resizeEnable: false,
        dragEnable: false,
        keyboardEnable: false,
        doubleClickZoom: false,
        zoomEnable: false,
        rotateEnable: false
      }
      map.setStatus(mapConfig)
      if (value) {
        const position = [value.longitude, value.latitude]
        const marker = new AMap.Marker({
          icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
          position
        })

        map.add(marker)
        map.setFitView()

        marker.setAnimation('AMAP_ANIMATION_BOUNCE')
      }

      function select(e) {
        map.clearMap()
        placeSearch.setCity(e.poi.adcode)
        placeSearch.search(e.poi.name) //关键字查询查询
      }

      const auto = new AMap.Autocomplete({
        input: 'tipinput'
      })
      const handleSelect = e => {
        try {
          const data = e.selected.data
          const res = {
            prov: data.pname,
            city: data.cityname,
            area: data.adname,
            map_locate: `${data.pname}${data.cityname}${data.adname}${data.address}`,
            latitude: data.location.Q,
            longitude: data.location.R
          }
          onChange(res)
          triggerCallback(res.map_locate)
        } catch (error) {
          console.log('handleSelect error', error)
        }
      }

      AMap.event.addListener(auto, 'select', select) //注册监听，当选中某条记录时会触发
      AMap.event.addListener(placeSearch, 'selectChanged', handleSelect) //注册监听，当选中某条记录时会触发
    } catch (error) {
      // console.log('AMap error', error)
    }
  }

  return (
    <>
      <div style={{ display: 'flex', marginBottom: '12px' }}>
        <div className={styles.location_tip}>
          {value?.map_locate || '请在下方地图内操作自提点的具体地图位置信息'}
        </div>
      </div>
      <div className={styles.map_content}>
        <div id='container' style={{ width: '900px', height: '500px' }}></div>
        {disabled ? null : (
          <>
            <div id='panel' className={styles.search_panel}></div>
            <Form.Item className={styles.map_search_input} label='搜索'>
              <Input id='tipinput'></Input>
            </Form.Item>
          </>
        )}
      </div>
    </>
  )
}

//  营业时间组件
const BusinessHours = props => {
  const { value, onChange, disabled } = props
  const [timeType, setTimeType] = useState(1)
  const [timeList, setTimeList] = useState([null])

  useEffect(() => {
    if (timeType === 1) {
      onChange(1)
    } else if (timeType === 2) {
      if (timeList.some(i => !i)) {
        onChange(null)
      } else {
        onChange(timeList)
      }
    }
  }, [timeType, timeList])

  useEffect(() => {
    if (value) {
      if (value === 1) {
        setTimeType(1)
      } else {
        setTimeType(2)
        setTimeList(value)
      }
    }
  }, [])

  const handleSetTimeType = e => {
    setTimeType(e.target.value)
  }

  const addTime = e => {
    const t = [...timeList, null]
    setTimeList(t)
  }

  const removeItem = idx => {
    const t = [...timeList]
    t.splice(idx, 1)
    setTimeList(t)
  }

  const handleSelectTime = (idx, time, timeString) => {
    const t = [...timeList]
    t[idx] = timeString
    setTimeList(t)
  }

  return (
    <Space direction='vertical'>
      <Radio.Group disabled={disabled} onChange={handleSetTimeType} value={timeType}>
        <Space direction='vertical'>
          <Radio value={1}>全天24小时</Radio>
          <Radio value={2}>自定义</Radio>
        </Space>
      </Radio.Group>
      {timeType === 2 ? (
        <Space direction='vertical' className={styles.time_picker_block}>
          <Radio disabled={disabled} checked={true}>
            每天重复
          </Radio>
          {timeList.map((i, idx) => (
            <div key={idx}>
              <RangePicker
                disabled={disabled}
                value={i ? [dayjs(i[0], 'HH:mm'), dayjs(i[1], 'HH:mm')] : []}
                format='HH:mm'
                onChange={(time, timeString) => handleSelectTime(idx, time, timeString)}
                disabledTime={n => ({
                  disabledHours: () => {
                    return timeList
                      .filter(i => i)
                      .map(i => [...Array(Number(i[1].split(':')[0]) + 1).keys()].slice(Number(i[0].split(':')[0])))
                      .flat()
                  }
                })}
              ></RangePicker>
              {disabled ? null : (
                <Button type='link' onClick={e => removeItem(idx)}>
                  删除
                </Button>
              )}
            </div>
          ))}
          {disabled ? null : (
            <Button type='link' onClick={addTime}>
              添加时间
            </Button>
          )}
        </Space>
      ) : null}
    </Space>
  )
}

// 表单主组件
export default () => {
  const [searchParams] = useSearchParams()
  const [form] = Form.useForm()
  const { SaveOwnTake, GetOwnTakeDetail } = useModel('Deliver')
  const pageType = Number(searchParams.get('type')) || 1
  const disabled = pageType === 3
  const id = searchParams.get('id')

  const { message } = App.useApp()

  const { contentWidth } = useModel('Global')
  const [FormList, setFormList] = useState([])
  const [initialValues, setInitialValues] = useState(originInitial)

  // SetFormRef(form);

  const defaultFormList = [
    {
      title: '',
      type: 'wrapper',
      children: [
        {
          title: '自提点名称',
          type: 'input',
          formProp: {
            name: 'name',
            label: '自提点名称',
            rules: [{ required: true, message: '请输入自提点名称！' }],
            help: '自提点名称不能超过20个字'
          },
          itemProp: {
            placeholder: '请输入自提点名称',
            style: { width: '346px' }
          }
        },
        {
          title: '启用状态',
          type: 'radio',
          visibelCheck: true,
          formProp: {
            name: 'status',
            label: '启用状态',
            rules: [{ required: true }]
          },
          itemProp: {
            prop: {},
            list: [
              {
                label: '启用',
                value: 1
              },
              {
                label: '禁用',
                value: 0
              }
            ]
          }
        },
        {
          title: '地图定位',
          type: 'location',
          formProp: {
            label: '地图定位',
            name: 'locationInfo',
            rules: [{ required: true, message: '请确认地图定位！' }]
          }
        },
        {
          title: '具体地址',
          type: 'input',
          formProp: {
            name: 'detail_address',
            label: '具体地址',
            rules: [{ required: true, message: '请输入具体地址！' }]
          },
          itemProp: {
            placeholder: '请输入具体地址',
            style: { width: '346px' }
          }
        },
        {
          title: '联系电话',
          type: 'inputNumber',
          formProp: {
            label: '联系电话',
            name: 'tel',
            rules: [{ required: true, message: '请输入联系电话！' }],
          },
          itemProp: {
            placeholder: '填写准确的联系电话，便于用户联系',
            style: { width: '346px' },
          }
        },
        {
          title: '自提时间',
          type: 'checkbox',
          formProp: {
            label: '自提时间',
            name: 'zt_time_flag',
            help: '勾选后，用户下单选择上门自提，必须选择自提时间，你需要按约定时间备货。若不勾选，将会提示用户按照与商家营业时间或约定的时间到店自提',
            valuePropName: 'checked',
            getValueFromEvent: e => (e.target.checked ? 1 : 0)
          },
          itemProp: {
            list: [
              {
                label: '需要用户选择自提时间'
              }
            ]
          }
        },
        {
          title: '营业时间',
          type: 'cusTimerPicker',
          formProp: {
            label: '营业时间',
            name: 'business_hours_flag',
            rules: [{ required: true, message: '请设置营业时间！' }],
            help: '买家可选的自提时间会根据该营业时间范围确定',
            validateTrigger: 'onBlur'
          },
          itemProp: {}
        }
      ]
    }
  ]

  useEffect(() => {
    // SetDisable(disabled);

    init()
    setFormList([...defaultFormList])

    return () => {
      if (timer) {
        clearTimeout(timer)
        timer = null
      }
    }
  }, [])

  const goEdit = () => {
    history.replace(`/pickupPoint?type=2&id=${id}`)
  }

  const handleTempStorage = () => {
    timer = setTimeout(() => {
      const data = form.getFieldsValue()
      localStorage.setItem('tempPickupPointStorage', JSON.stringify(data))
      handleTempStorage()
    }, 5000)
  }

  const init = () => {
    if (pageType === 1) {
      // 新增
      const data = localStorage.getItem('tempPickupPointStorage')

      if (data && data !== '{}') {
        const temp = JSON.parse(data)
        setInitialValues(temp)
        form.resetFields()
        setTimeout(() => {
          form.resetFields()
        }, 100)
      }

      handleTempStorage()
    } else {
      // 编辑
      if (id) {
        getPickupPointInfo()
      } else {
        message.error('商品ID有误')
      }
    }
  }

  const getPickupPointInfo = async () => {
    const res = await GetOwnTakeDetail({ id })
    if (res) setPickupPointInfo(res)
  }

  const setPickupPointInfo = data => {
    const formData = {
      ...data,
      locationInfo: {
        ...data
      },
      business_hours_flag: data.business_hours_flag === 1 ? 1 : data.custom_time
    }
    setInitialValues(formData)
    setTimeout(() => {
      form.resetFields()
    }, 200)
  }

  const formatMenuList = list => {
    if (list && list.length) {
      return list.map(i => ({
        title: i.menu_name,
        key: i.id,
        icon: i.menu_icon ? (
          <svg className={styles.icon} aria-hidden='true'>
            <use xlinkHref={i.menu_icon}></use>
          </svg>
        ) : null,
        children: formatMenuList(i.children)
      }))
    } else {
      return []
    }
  }

  const onSubmit = () => {
    console.log(form.getFieldsValue())
    form
      .validateFields()
      .then()
      .catch(err => {
        if (err.errorFields.length) {
          message.warning('请完善表单必要信息')
        }
      })
    form.submit()
  }

  const onReset = () => {
    setInitialValues(originInitial)
    localStorage.removeItem('tempPickupPointStorage')
    form.resetFields()
    setTimeout(() => {
      form.resetFields()
    }, 100)
  }

  const onFinish = async e => {
    const { locationInfo, business_hours_flag } = e
    const params = {
      ...locationInfo,
      ...e,
    }

    if (business_hours_flag !== 1) {
      params.business_hours_flag = 2
      params.custom_time = business_hours_flag
    }

    if (pageType === 2 && id) {
      params.id = id
    }

    const res = await SaveOwnTake(params)
    if (res && res.id) {
      message.success('操作成功')
      localStorage.removeItem('tempPickupPointStorage')
      history.replace(`/pickupPoint?type=3&id=${res.id}`)
    }
  }

  const handleLocationCallback = data => {
    form.setFieldValue('detail_address', data)
  }

  const renderFormList = list => {
    return list.map(formItem => {
      const { type, title, children, formProp, itemProp, component, options } = formItem

      switch (type) {
        case 'wrapper':
          return (
            <Card title={title} key={title} style={{ marginBottom: '16px' }}>
              {component ? component : renderFormList(children)}
            </Card>
          )
        case 'subWrapper':
          return (
            <Card
              title={title}
              key={title}
              bordered={false}
              headStyle={{ border: 'none' }}
              style={{ boxShadow: 'none' }}
              bodyStyle={{ padding: 0 }}
            >
              {component ? component : renderFormList(children)}
            </Card>
          )
        case 'formComponent':
          return (
            <Form.Item {...formProp} key={title}>
              {component}
            </Form.Item>
          )
        case 'input':
          return (
            <Form.Item {...formProp} key={title}>
              <Input disabled={disabled} {...itemProp} />
            </Form.Item>
          )
        case 'inputNumber':
          return (
            <Form.Item {...formProp} key={title}>
              <InputNumber disabled={disabled} {...itemProp} />
            </Form.Item>
          )
        case 'radio':
          return (
            <Form.Item {...formProp} key={title}>
              <Radio.Group disabled={disabled} {...itemProp.prop}>
                {options === 'vertical' ? (
                  <Space direction='vertical' style={{ paddingTop: '5px' }}>
                    {itemProp.list && itemProp.list.length
                      ? itemProp.list.map(radio => (
                          <Radio value={radio.value} key={radio.value}>
                            {radio.label}
                          </Radio>
                        ))
                      : null}
                  </Space>
                ) : itemProp.list && itemProp.list.length ? (
                  itemProp.list.map(radio => (
                    <Radio value={radio.value} key={radio.value}>
                      {radio.label}
                    </Radio>
                  ))
                ) : null}
              </Radio.Group>
            </Form.Item>
          )
        case 'checkbox':
          return (
            <Form.Item {...formProp} key={title}>
              {itemProp.list.map(i => (
                <Checkbox disabled={disabled} key={i.label}>
                  {i.label}
                </Checkbox>
              ))}
            </Form.Item>
          )
        case 'select':
          return (
            <Form.Item {...formProp} key={title}>
              <Select disabled={disabled} {...itemProp.prop} />
            </Form.Item>
          )
        case 'cascader':
          return (
            <Form.Item {...formProp} key={title}>
              <Cascader disabled={disabled} {...itemProp} />
            </Form.Item>
          )
        case 'location':
          return (
            <Form.Item {...formProp} key={title}>
              <LocationPickup disabled={disabled} triggerCallback={handleLocationCallback}></LocationPickup>
            </Form.Item>
          )
        case 'cusTimerPicker':
          return (
            <Form.Item {...formProp} key={title}>
              <BusinessHours disabled={disabled}></BusinessHours>
            </Form.Item>
          )
      }
    })
  }

  const formatExtra = () => {
    return pageType === 3
      ? [
          <Button key='goedit' htmlType='reset' onClick={goEdit}>
            编辑
          </Button>
        ]
      : [
          <Button key='reset' htmlType='reset' onClick={onReset}>
            重置
          </Button>,
          <Button key='submit' type='primary' onClick={onSubmit}>
            保存
          </Button>
        ]
  }

  useEffect(() => {
    document.getElementsByClassName('ant-page-header')[0].style.width = `${contentWidth}px`
  }, [contentWidth])

  return (
    <div className={styles.point_wrapper}>
      <PageContainer
        header={{
          fixedHeader: true,
          title: (
            <div className={styles.header_title}>
              <span>{pageType === 2 ? '编辑自提点' : pageType === 3 ? '自提点详情' : '新建自提点'}</span>
              <Divider type='vertical' />
              <span className={styles.header_desc}>自提点地址管理页</span>
            </div>
          ),
          extra: formatExtra()
        }}
      >
        <Form form={form} name='goods_form' {...formItemLayout} onFinish={onFinish} initialValues={initialValues}>
          {renderFormList(FormList)}
        </Form>
      </PageContainer>
    </div>
  )
}
